
export class Algorithm
{
    /**
     * 循环版二分查找
     *
     * @param nums  数组
     * @param n     数组长度
     * @param value 要查找的值
     * @return
     */
    public  static   bSerachIndex<T extends PriorityItem>( arr:T[],item:T,compare:(a:T,b:T)=>boolean):number {
        let low = 0;
        let high = arr.length - 1;
        const getMid=()=>
        {
            while (low <= high) {
                // 找出中间下标 
                let mid = low + ((high - low) >> 1);
                if (arr[mid].priority > item.priority) {
                    low = mid - 1;
                } else if (arr[mid].priority < item.priority) {
                    high = mid + 1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
        
        const mid = getMid();
        if(mid>=0)
        {
            let low = mid-1;let high=mid;
            for(let i=low;i>=0  ;i--)
            {
                if(arr[i].priority!=item.priority)
                {
                    break;
                }
                if(compare(arr[i],item))
                {
                    return i;
                }
                 
            }
            for(let i=high;i<arr.length  ;i++)
            {
                if(arr[i].priority!=item.priority)
                {
                    break;
                }
                if(compare(arr[i],item))
                {
                    return i;
                }
            }
        }

        return -1;
    }
}